const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

// 模拟用户数据
let users = [
  { id: 1, username: 'admin', password: bcrypt.hashSync('admin123', 10), role: 'admin' },
  { id: 2, username: 'user', password: bcrypt.hashSync('user123', 10), role: 'user' }
];

// 模拟用户列表
let userList = [
  { id: 1, username: 'admin', role: '核心技术人' },
  { id: 2, username: 'user', role: '测试用户' }
];

// 登录接口
app.post('/api/login', async (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username);
  
  if (!user || !(await bcrypt.compare(password, user.password))) {
    return res.status(401).json({ message: '用户名或密码错误' });
  }

  const token = jwt.sign({ id: user.id, username: user.username, role: user.role }, 'secret_key', { expiresIn: '1h' });
  res.json({ token });
});

// 获取用户列表
app.get('/api/users', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ message: '未登录' });

  jwt.verify(token, 'secret_key', (err, decoded) => {
    if (err) return res.status(401).json({ message: 'token 无效' });
    res.json(userList);
  });
});

// 添加用户
app.post('/api/users', (req, res) => {
  const { username, role } = req.body;
  const newUser = { id: userList.length + 1, username, role };
  userList.push(newUser);
  res.json(newUser);
});

// 删除用户
app.delete('/api/users/:id', (req, res) => {
  userList = userList.filter(u => u.id !== parseInt(req.params.id));
  res.json({ message: '删除成功' });
});

// 更新用户
app.put('/api/users/:id', (req, res) => {
  const { username, role } = req.body;
  const user = userList.find(u => u.id === parseInt(req.params.id));
  if (user) {
    user.username = username;
    user.role = role;
    res.json(user);
  } else {
    res.status(404).json({ message: '用户不存在' });
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));